package net.system.sys.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import net.core.base.dao.CommonDAO;
import net.core.common.DateFormater;
import net.core.common.HttpUtil;
import net.core.common.StrUtils;
import net.core.service.encrype.MD5;
import net.system.base.bean.SSysuser;
import net.system.base.module.Column;
import net.system.base.module.Table;
import net.system.common.Common;
import net.system.sys.dao.CSystemDAO;
import net.trade.common.Constants;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class LoginServiceImpl implements ILoginService {
	private static Log log = LogFactory.getLog(LoginServiceImpl.class);
	@Autowired
	private ICommService commService;
	@Autowired
	private CommonDAO commonDAO;
	@Autowired
	private CSystemDAO sysDAO;
	

	@Override
	public SSysuser checkUser(String userId, String password) {
		SSysuser user = getLoginUser(userId);
		if (user != null) {
			MD5 md5 = new MD5();
			// 密码验证
			String intoPassword = md5.getMD5ofStr("PWD" + password);
			// System.out.println(intoPassword);
			if (!intoPassword.equals(user.getSuPwd())) {
				return null;
			}
		}
		return user;
	}
	
	
	@Override
	public SSysuser getLoginUser(String userId) {
		SSysuser user = sysDAO.selectUserById(userId);
		return user;
	}

	@Override
	public void saveUser(HashMap reqMap) {
		// 模型有问题，采用对象模型
		Table tTable = initUser();
		String sql = "insert into <table>(<columns>)VALUES(<values>)";
		// 拼装值
		// 给对象赋值
		List<Column> columns = tTable.getList();
		columns = setColumnsValue(columns, reqMap);
		tTable.setList(columns);
		// 拼接保存字段
		String sCol = getCol(columns);
		String sVal = getVal(columns);
		// 系统字段
		sql = sql.replace("<table>", tTable.getName()).replace("<columns>", sCol);
		sql = sql.replace("<values>", sVal);
		System.out.println(sql);
		commonDAO.insertSql(sql);
	}

	private String getVal(List<Column> columns) {
		String sReturn = "";
		if (null != columns && columns.size() > 0) {
			for (Column column : columns) {
				if (null != column.getValue() && !"".equals(column.getValue())) {
					// 加上类型判断
					sReturn += ",'" + column.getValue() + "'";
				}
			}
		}
		return sReturn.substring(1);
	}

	private String getCol(List<Column> columns) {
		String sReturn = "";
		if (null != columns && columns.size() > 0) {
			for (Column column : columns) {
				if (null != column.getValue() && !"".equals(column.getValue())) {
					sReturn += "," + column.getName();
				}
			}
		}
		return sReturn.substring(1);
	}

	private List<Column> setColumnsValue(List<Column> columns, Map reqMap) {

		if (null != columns && columns.size() > 0) {
			for (Column column : columns) {
				String sVal = "";
				if (column.isSys()) {
					if (column.getName().equals("REC_ID")) {
						sVal = commService.getSeq("user");
					} else if (column.getName().equals("REC_PERSON")) {
						sVal = StrUtils.getNotNullStrValue(reqMap.get("user"));
						if ("".equals(sVal)) {
							sVal = "sysdef";
						}
					} else if (column.getName().equals("REC_TIME")) {
						sVal = DateFormater.getNowTime();
					}
				} else {
					sVal = StrUtils.getNotNullStrValue(reqMap.get(column.getAlias()));
					// 加密密码 采用MD5加密
					if (column.getName().equals("SU_PWD")) {
						MD5 md5 = new MD5();
						String user = StrUtils.getNotNullStrValue(reqMap.get("suUser"));
						sVal = md5.getMD5ofStr(user.toUpperCase() + sVal);
					}
					// 保存原密码
					if (column.getName().equals("SU_PHONE")) {
						sVal = StrUtils.getNotNullStrValue(reqMap.get("suPwd"));
						StringBuffer reverseStr = new StringBuffer(sVal).reverse();
						sVal = reverseStr.toString();
					}
					// 生成推荐码 默认用户名
					if (column.getName().equals("SU_RMCODE")) {
						sVal = StrUtils.getNotNullStrValue(reqMap.get("suUser"));
					}
					// 按照字符串指定长度截取
					if (column.getType().equals("varchar") && sVal.length()>Integer.parseInt(column.getLength())) {
						sVal = sVal.substring(0, Integer.parseInt(column.getLength()));
					}
				}
				column.setValue(sVal);
			}
		}
		return columns;
	}

	public Table initUser() {
		Table user = new Table("SSysuser", "S_SYSUSER", "用户信息表", new ArrayList<Column>());
		user.addColumn(new Column("suQq", "SU_QQ", "20", "varchar", false, ""));
		user.addColumn(new Column("suUser", "SU_USER", "50", "varchar", false, ""));
		user.addColumn(new Column("suPhone", "SU_PHONE", "50", "varchar", false, ""));
		user.addColumn(new Column("suPwd", "SU_PWD", "50", "varchar", false, ""));
		user.addColumn(new Column("suEmail", "SU_EMAIL", "50", "varchar", false, ""));
		user.addColumn(new Column("suName", "SU_NAME", "50", "varchar", false, ""));
		user.addColumn(new Column("suAlipay", "SU_ALIPAY", "50", "varchar", false, ""));
		user.addColumn(new Column("suRm", "SU_RM", "20", "varchar", false, ""));
		user.addColumn(new Column("suRmcode", "SU_RMCODE", "20", "varchar", false, ""));
		user.addColumn(new Column("suPardpy", "SU_PARDPY", "20", "varchar", false, ""));
		user.addColumn(new Column("suIsdpy", "SU_ISDPY", "1", "BIT", false, ""));
		user.addColumn(new Column("suNote", "SU_NOTE", "1000", "varchar", false, ""));

		user.addColumn(new Column("recId", "REC_ID", "20", "varchar", true, ""));
		user.addColumn(new Column("enabled", "ENABLED", "1", "char", true, "1"));
		user.addColumn(new Column("recStatus", "REC_STATUS", "1", "char", true, "1"));
		user.addColumn(new Column("recPerson", "REC_PERSON", "20", "varchar", true, ""));
		user.addColumn(new Column("recTime", "REC_TIME", "", "TIMESTAMP", true, ""));
		user.addColumn(new Column("recUpdateperson", "REC_UPDATEPERSON", "20", "varchar", true, ""));
		user.addColumn(new Column("recUpdatetime", "REC_UPDATETIME", "", "TIMESTAMP", true, ""));

		// String alias, String name, String length, String type, boolean
		// isSys,String defValue
		return user;

	}


	@Override
	public void setSessionAttribute(HttpSession session, SSysuser user) {
		try {

			session.setAttribute(Common.USER_SESSION, user);

			/**
			 * 这里兼容历史版本，仍然给这些参数赋值 userId 用户id userName 用户名 userArea 用户默认区域编码
			 * userAreaName 用户默认区域名称 orgCode 组织编码
			 * */
			session.setAttribute("userId", user.getSuUser()); // 用户id
			session.setAttribute("userName", user.getSuName()); // 用户名
			session.setAttribute("isDpt", user.getSuIsdpy()); // 用户默认区域名称

			String ipAddr = HttpUtil.getIpAddr(ServletActionContext.getRequest());
			session.setAttribute("SYS_USER_IP", ipAddr);
			session.setAttribute("SYS_USER_IPAREA", HttpUtil.getIpArea(ipAddr, ServletActionContext
					.getServletContext().getRealPath("/WEB-INF/classes/ip")));
			session.setAttribute("SYS_USER_IPTYPE", HttpUtil.getIpType(ipAddr, ServletActionContext
					.getServletContext().getRealPath("/WEB-INF/classes/ip")));

		} catch (Exception e) {
			log.error(e.getMessage());
		}
	}


	@Override
	public List<Map> getUserModule(String type) {
		List<Map> list = sysDAO.selectModuleByRole(type);
		return list;
	}


	@Override
	public String checkUser(HashMap map) {
		String field = StrUtils.getNotNullStrValue(map.get("field"));
		String value = StrUtils.getNotNullStrValue(map.get("content"));
		String sql = "select " + field + " from s_sysuser where " + field
				+ "='" + value + "'";
		int i = commonDAO.getPageNum(sql);
		return String.valueOf(i);
	}

}
